package com.jabex.manager.listener;


import com.jabex.manager.actions.Controller;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;

import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;


/**
 * Created by Jerges Bello on 15/07/2014.
 *
 */
public class LoginErrorPhaseListener extends Controller implements PhaseListener {
    private static final long serialVersionUID = -1216620620302322995L;

    @Override
    public void beforePhase(final PhaseEvent arg0)
    {
        Exception e = (Exception) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(
		        WebAttributes.AUTHENTICATION_EXCEPTION);


	    if (e instanceof BadCredentialsException)
        {
            FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(
		            WebAttributes.AUTHENTICATION_EXCEPTION, null);
	        super.setFunctionalErrorMessage("login.error.not.valid");
        }
    }

    @Override
    public void afterPhase(final PhaseEvent arg0)
    {}

    @Override
    public PhaseId getPhaseId()
    {
        return PhaseId.RENDER_RESPONSE;
    }

}
